package ycl.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前端工具
 *
 * @author ycl
 * @date 2022-03-09 20:14:17
 */
public class ServletUtil {


	public static void setResultResponse(HttpServletResponse response) {
		response.setHeader("ContentType", "text/json");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
	}


	public static HttpServletRequest getHttpServletRequest() {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		assert attributes != null;
		return attributes.getRequest();
	}

	public static final String REMOTE_UNKNOWN = "unknown";

	/**
	 * 获取用户ip
	 *
	 * @param request 请求
	 * @return
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		if (request == null)
			return REMOTE_UNKNOWN;
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || REMOTE_UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");

		if (ip == null || ip.length() == 0 || REMOTE_UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("X-Forwarded-For");

		if (ip == null || ip.length() == 0 || REMOTE_UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");

		if (ip == null || ip.length() == 0 || REMOTE_UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("X-Real-IP");

		if (ip == null || ip.length() == 0 || REMOTE_UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();

		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip.split(",")[0];
	}

}
